package com.zuoshenge.tool;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Utils {

   final static Base64.Encoder encoder = Base64.getEncoder();
   final static Base64.Decoder decoder = Base64.getDecoder();

   public static String encode(String text) {
      byte[] textByte = new byte[0];
      try {
         textByte = text.getBytes("UTF-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      String encodedText = encoder.encodeToString(textByte);
      return encodedText;
   }

  
   public static String decode(String encodedText) {
      String text = null;
      try {
         text = new String(decoder.decode(encodedText), "UTF-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      return text;
   }

   public static MultipartFile convertBase64ToMultipart(String base64Image, String fileName) throws IOException {
      // 去除base64字符串中的前缀（如果有的话）
      String base64Data = base64Image.replaceFirst("data:image/png;base64,", "").replaceFirst("data:image/jpeg;base64,", "");

      // 解码base64字符串为字节数组
      byte[] imageBytes = Base64.getDecoder().decode(base64Data);

      // 创建ByteArrayResource
      ByteArrayResource resource = new ByteArrayResource(imageBytes);

      // 使用MockMultipartFile来创建MultipartFile对象
      MultipartFile multipartFile = new MockMultipartFile(
              "file", // 参数名
              fileName, // 文件名
              "image/png", // 文件类型
              resource.getInputStream() // 输入流
      );

      return multipartFile;
   }
}